package com.renchunlin.banner.view

import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/14.
 * PS: Not easy to write code, please indicate.
 */
class LoopViewPager : ViewPager {

    private var mHandler: Handler = Handler(Looper.getMainLooper())

    constructor(context: Context) : this(context, null){
        setPageTransformer(true
        ) { _, _ ->  }
    }

    @SuppressLint("ClickableViewAccessibility")
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
        setOnTouchListener { _, p1 -> //不处理事件
            when (p1.action) {
                MotionEvent.ACTION_DOWN -> {
                    pauseLooper()
                }
                MotionEvent.ACTION_CANCEL -> {
                    resumeLooper()
                }
                MotionEvent.ACTION_UP -> {
                    resumeLooper()
                }
            }
            false
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        this.resumeLooper()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        this.pauseLooper()
    }

    private fun resumeLooper() {
        //继续轮播
        mHandler.postDelayed(mTask, 1000)
    }

    private val mTask: Runnable = object : Runnable {
        override fun run() {
            var currentItem = currentItem
            currentItem++
            setCurrentItem(currentItem)
            mHandler.postDelayed(this, 1000)
        }
    }

    private fun pauseLooper() {
        //暂停轮播
        mHandler.removeCallbacks(mTask)
    }
}